<template>
  <div class="app-container">
    <van-form ref="formRef" label-align="top">
      <van-cell-group>
        <van-field class="problem_desc_warp" v-model="form.content" placeholder="您好，请简要描述您的问题或者建议" label="问题描述"
          name="pattern" required type="textarea" maxlength="1000" rows="2" :rules="[{ required: true, }]" />
        <van-field name="uploader" label="上传问题截图" class="uploader_warp">
          <template #input>
            <van-uploader v-model="fileList" multiple :max-count="3" :before-read="beforeRead" :after-read="afterRead"
              :before-delete="beforeDelete"
              accept="image/gif,image/jpg,image/jpeg, image/png, image/webp, video/mp4,video/avi" />
          </template>
        </van-field>
        <van-field v-model="form.contactInfo" label="联系方式" name="pattern" placeholder="请留下您的邮箱/手机号/QQ号" />
      </van-cell-group>
      <div class="page_footer_warp">
        <div class="s_btn_warp">
          <van-button type="primary" @click="onSubmit">提交</van-button>
        </div>
      </div>
    </van-form>
  </div>
</template>
<script setup lang="ts">
import { addFeedbacks } from '@/api/album/feedback/submit'
import { uploadFile } from "@/api/album/public/index"
import { ref, onBeforeUnmount } from 'vue';
import { showToast, showSuccessToast, showFailToast } from 'vant';

// let test_token = 'eyJhbGciOiJIUzI1NiJ9.eyJ1c2VySWQiOjI0LCJ1c2VybmFtZSI6InVzZWZ4dGVzdCIsInN1YiI6InVzZWZ4dGVzdCIsImlhdCI6MTc1NTgzNTQxMywiZXhwIjoxNzU2NDQwMjEzfQ.9bIEuXMhIR0fz_-9JdORSbna0rPjgwErMKiuMuOMLcE'
// let token = test_token
let token = ''
let userData: any = {
  phoneModel: ''
}
// Android/iOS JS互传数据

// 接收来自原生应用的消息
function receiveUserData(message: any) {
  try {
    // 可以在这里处理来自原生应用的数据
    token = message.token
    userData.phoneModel = message.phoneModel
  } catch (error) {
    console.error('处理原生应用消息出错:', error);
  }
}
(window as any).receiveUserData = receiveUserData;

const form: any = ref({
  content: "",
  filePath: [] as string[], // 明确类型为 string[],
  contactInfo: "",
});
const fileList = ref([]);
const formRef = ref();

// 每张图片上传之前的判断
const beforeRead = (file: any) => {
  if (!isImage(file.name) && !isVideo(file.name)) {
    showToast('请上传.gif、.jpg、.jpeg、.png、.webp格式图片或.mp4、.avi格式视频');
    return false;
  }
  const maxSize = 5,
    isLtMax = file.size / 1024 / 1024 < maxSize;
  if (!isLtMax) {
    showToast(`图片大小不能超过${maxSize}MB`);
    return false;
  }
  return true;
};

/**
 * 上传状态
 * @afterRead 总事务
 * 
 * @handleStatus 处理返回结果重复逻辑
 * @status 上传成功与否 true 成功 false 失败
 * @index 数组的下标
 */
const handleStatus = (index: any, status: Boolean, file: any, successUrl: String = '') => {
  if (status) {
    // form.value.filePath.splice(index, 0, successUrl);
    form.value.filePath[index] = successUrl
    file.status = 'success';
    file.message = '上传成功';
    return
  }

  // form.value.filePath.splice(index, 0, '');
  form.value.filePath[index] = ''
  file.status = 'failed';
  file.message = '上传失败';
}
const afterRead = (file: any, arrList: any) => {
  file.status = 'uploading';
  file.message = '上传中...';

  let params: any = new FormData();
  params.append("type", 4);
  params.append("file", file.file);

  uploadFile(params, token).then(res => {
    const data = res.data;
    if (data.code === 200) {
      handleStatus(arrList.index, true, file, data.data)
    } else {
      handleStatus(arrList.index, false, file)
    }
  }).catch(error => {
    handleStatus(arrList.index, false, file)
  })
};

const beforeDelete = (file: any, arrList: any) => {
  form.value.filePath.splice(arrList.index, 1)
  return true
}

// 表单提交
const onSubmit = async () => {
  let is_v = submitValidatorShowToast()
  if (is_v) {
    return
  }
  let params = { ...form.value };
  params.phoneModel = userData.phoneModel
  try {
    params.filePath = params.filePath ? params.filePath.join() : ''
  } catch (error) {
    showFailToast('参数有问题');
    return;
  }

  formRef.value
    ?.validate()
    .then(() => {
      addFeedbacks(params, token).then(res => {
        const data = res.data;
        if (data.code === 200) {
          showSuccessToast('提交成功');
        } else {
          showFailToast('提交失败');
        }
      }).catch(error => {
        showFailToast('请查看是否登录成功，重新提交');
      })
    })
    .catch(() => {
      console.log('验证失败');
    });
};

// 单独重新验证字段提示
const submitValidatorShowToast = () => {
  const valid: any = {
    content: '问题描述'
  }
  for (let key in valid) {
    let el = valid[key];
    if (!form.value[key]) {
      showToast(`${el}字段为必须`);
      return true
    }
  }
  return false
}

const isImage = (name: any) => {
  return /\.(gif|jpg|jpeg|png|webp)$/.test(name)
}
const isVideo = (name: any) => {
  return /\.(mp4|avi)$/.test(name)
}
// 在组件完全卸载之前移除事件监听器
onBeforeUnmount(() => {
  (window as any).receiveUserData = undefined
});
</script>
<style scoped lang="scss">
$page_p_t: 18px;
$page_p_b: 92px;
$page_bgc: #f5f5f5;
$page_font_size: 14px;
$input_bgc: #fff;
$com_border_radius: 12px;
$page_padding_LR: 16px;
$van-uploader-size: 60px;


@mixin com_input_s {
  background-color: $input_bgc;
  border-radius: $com_border_radius;
  padding: 14px 8px;
  line-height: 20px;
  font-size: $page_font_size;
}

@mixin com_textarea_s {
  @include com_input_s;
  padding: 8px;
}

.app-container {
  height: 100%;
  position: relative;
  display: flex;
  flex-direction: column;
  background-color: $page_bgc;
  overflow: auto;
}

::v-deep {
  .van-form {
    padding-top: $page_p_t;
    padding-bottom: $page_p_b;
    flex: 1;
    height: 100%;
    max-height: calc(100% - $page_p_t - $page_p_b);
    position: relative;
    overflow: auto;
  }

  .van-cell {
    padding: 0 $page_padding_LR 24px;
    background-color: $page_bgc;

    &:after {
      display: none;
    }

    input {
      @include com_input_s;
    }
  }

  .van-cell-group {
    background-color: $page_bgc;
    overflow: auto;
    max-height: 100%;

    &::after {
      display: none;
    }
  }

  .van-field__label--top {
    margin-bottom: 16px;
    font-size: 12px;
    line-height: 20px;
    color: #15181D
  }

  .problem_desc_warp {
    textarea {
      height: 170px;
      @include com_textarea_s;
    }
  }

  .van-field__label--required {
    &::before {
      display: none;
    }

    &::after {
      content: "*";
      color: #F44755;
    }
  }

  .uploader_warp {
    &.van-cell {
      padding-bottom: 16px;
    }
  }

  .van-uploader__preview {

    .van-image,
    .van-uploader__mask {
      border-radius: $com_border_radius;
      width: $van-uploader-size;
      height: $van-uploader-size;
    }

    .van-uploader__preview-delete {
      border-radius: 50%;
      top: 4px;
      right: 4px;
    }
  }

  .van-uploader__upload {
    background-color: $input_bgc;
    border-radius: $com_border_radius;
    width: $van-uploader-size;
    height: $van-uploader-size;

    .van-uploader__upload-icon {
      font-size: 24px;
    }

    .van-uploader__input {
      padding: 0;
    }
  }

  .page_footer_warp {
    padding: 0 $page_padding_LR 24px;
    position: absolute;
    left: 0;
    bottom: 0;
    width: calc(100% - $page_padding_LR * 2);
  }

  .s_btn_warp {
    background-color: $page_bgc;


    .van-button {
      width: 100%;
      height: 48px;
      border: none;
      border-radius: 8px;
      background-color: #15181D;
      color: #fff;
      font-size: $page_font_size;
    }
  }
}
</style>